/*
 *  Copyright 2004 Blandware (http://www.blandware.com)
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package com.blandware.atleap.persistence.hibernate.core;

import com.blandware.atleap.common.util.PartialCollection;
import com.blandware.atleap.common.util.QueryInfo;
import com.blandware.atleap.model.core.Layout;
import com.blandware.atleap.persistence.core.LayoutDAO;
import com.blandware.atleap.persistence.exception.DeleteException;
import com.blandware.atleap.persistence.exception.UpdateException;

import java.util.ArrayList;
import java.util.List;


/**
 * <p>Hibernate implementation of LayoutDAO</p>
 * <p><a href="LayoutDAOHibernate.java.html"><i>View Source</i></a></p>
 *
 * @author Sergey Zubtsovskiy <a href="mailto:sergey.zubtsovskiy@blandware.com">&lt;sergey.zubtsovskiy@blandware.com&gt;</a>
 * @version $Revision: 1.17 $ $Date: 2008/06/23 13:24:54 $
 */
public class LayoutDAOHibernate extends LocalizableDAOHibernate implements LayoutDAO {

	/**
	 * Creates new instance of LayoutDAOHibernate
	 */
	public LayoutDAOHibernate() {
	}

	/**
	 * @see com.blandware.atleap.persistence.core.LayoutDAO#createLayout(com.blandware.atleap.model.core.Layout)
	 */
	public Long createLayout(Layout layout) {
		return (Long) getHibernateTemplate().save(layout);
	}

	/**
	 * @see com.blandware.atleap.persistence.core.LayoutDAO#retrieveLayout(java.lang.Long)
	 */
	public Layout retrieveLayout(Long layoutId) {
		Object o = getHibernateTemplate().get(Layout.class, layoutId);
		if ( o instanceof Layout ) {
			return  (Layout) o;
		} else {
			return null;
		}
	}

	/**
	 * @see com.blandware.atleap.persistence.core.LayoutDAO#updateLayout(com.blandware.atleap.model.core.Layout)
	 */
	public void updateLayout(Layout layout) throws UpdateException {
        String cpDefinition = layout.getCpDefinition();
        if (cpDefinition == null || cpDefinition.length() == 0) {
    		String hql = "select p from Layout l, ContentPage p where l.id = ? and p.layout = l";
	    	List list = executeFind(hql, new Object[]{layout.getId()});
		    if ( list != null && list.size() > 0 ) {
			    String errorMessage = "Cannot update layout, because there is one or more content pages, based on it, so cpDefinition cannot be set to empty";
			    if ( log.isErrorEnabled() ) {
				    log.error(errorMessage);
    			}
	    		throw new UpdateException(errorMessage);
		    }
        }
		getHibernateTemplate().update(layout);
	}

	/**
	 * @see com.blandware.atleap.persistence.core.LayoutDAO#deleteLayout(com.blandware.atleap.model.core.Layout)
	 */
	public void deleteLayout(Layout layout) throws DeleteException {
		String hql = "select p from Layout l, ContentPage p where l.id = ? and p.layout = l";
		List list = executeFind(hql, new Object[]{layout.getId()});
		if ( list != null && list.size() > 0 ) {
			String errorMessage = "Cannot delete layout, because there is one or more content pages, based on it";
			if ( log.isErrorEnabled() ) {
				log.error(errorMessage);
			}
			throw new DeleteException(errorMessage);
		}
		getHibernateTemplate().delete(layout);
	}

	/**
	 * @see com.blandware.atleap.persistence.core.LayoutDAO#listLayouts(com.blandware.atleap.common.util.QueryInfo)
	 */
	public PartialCollection listLayouts(QueryInfo queryInfo) {
		String whereClause = new String();
		String orderByClause = new String();
		if ( queryInfo != null ) {
			whereClause = queryInfo.getWhereClause();
			orderByClause = queryInfo.getOrderByClause();
			if ( whereClause != null && whereClause.length() != 0 ) {
				whereClause = " where " + whereClause;
			} else {
				whereClause = new String();
			}
			if ( orderByClause != null && orderByClause.length() != 0 ) {
				orderByClause = " order by " + orderByClause;
			} else {
				orderByClause = new String();
			}
		}

		List list = null;
		Integer total = null;
		String hqlPart = "from Layout l" + whereClause;
		if ( queryInfo != null && (queryInfo.getLimit() != null || queryInfo.getOffset() != null) ) {
			String hqlForTotal = "select count(l.id) " + hqlPart;
			total = findUniqueIntegerResult(hqlForTotal);
			if ( total == null ) {
				total = new Integer(0);
			}
		}
        // If we don't have any info about the total number of results yet or
        // we know that there's something that will be found, then fetch data
		if ( total == null || total.intValue() > 0 ) {
			String hql = "select l " + hqlPart + orderByClause;
			list = executeFind(hql, queryInfo);
			if ( total == null ) {
				total = new Integer(list.size());
			}
		} else {
			list = new ArrayList();
		}
		return new PartialCollection(list, total);
	}

	/**
	 * @see com.blandware.atleap.persistence.core.LayoutDAO#hasDuplicates(com.blandware.atleap.model.core.Layout)
	 */
	public boolean hasDuplicates(Layout layout) {

		ArrayList args = new ArrayList();
		args.add(layout.getName());
		args.add(layout.getDefinition());

		String hql = "select count(l.id) from Layout l where (l.name = ? or l.definition = ?)";
		if ( layout.getId() != null ) {
			hql += " and l.id != ?";
			args.add(layout.getId());
		}

		int count = (findUniqueIntegerResult(hql, args.toArray())).intValue();

		return count > 0;
	}

	/**
	 * @see com.blandware.atleap.persistence.core.LayoutDAO#findLayoutByContentPageUri(java.lang.String)
	 */
	public Layout findLayoutByContentPageUri(String contentPageUri) {
		return (Layout) findUniqueResult("select p.layout from ContentPage p where p.uri = ?", new Object[]{contentPageUri});
	}

	/**
	 * @see com.blandware.atleap.persistence.core.LayoutDAO#findLayoutByDefinition(java.lang.String)
	 */
	public Layout findLayoutByDefinition(String definitionName) {
		return (Layout) findUniqueResult("from Layout l where l.definition = ?", new Object[]{definitionName});
	}

	/**
	 * @see com.blandware.atleap.persistence.core.LayoutDAO#findLayoutByName(java.lang.String)
	 */
	public Layout findLayoutByName(String name) {
		return (Layout) findUniqueResult("from Layout l where l.name = ?", new Object[]{name});
	}
}
